import json
import hashlib
import time
import uuid
import requests
import pprint


class Translation(object):
    def __init__(self, app_key, app_pwd):
        # 应用ID
        self.app_key = app_key
        # 应用密钥
        self.app_pwd = app_pwd
        # 请求参数字典
        self.data = {}
        # 请求头
        self.headers = {}
        # api地址
        self.api = "https://openapi.youdao.com/api"
        # 支持的语言字典
        self.language = {}
        # 请求结果
        self.response = None

    def set_language(self, path: str):
        """读取所有语言json文件"""
        with open(path, "r", encoding="utf-8") as f:
            self.language = json.load(f)

    def get_language(self) -> list:
        """
        获取所有可用语言
        :return: 可用语言列表
        """
        return list(self.language.keys())

    def get_input(self, q: str) -> str:
        """
        获取计算过后的要翻译的字符串
        :param q: 要翻译的文字
        :return: 计算后的结果
        """
        return q if len(q) <= 20 else q[:10] + len(q) + q[-10:]

    def get_sign(self, q: str) -> str:
        """
        计算签名后的sign参数
        :param q: 要翻译的文字
        :return: 签名后的sign参数
        """
        sha = hashlib.sha256()
        sha.update(
            (self.app_key + self.get_input(q) + self.data['salt'] + self.data['curtime'] + self.app_pwd).encode(
                'utf-8'))
        return sha.hexdigest()

    def set_data(self):
        """设置请求参数"""
        self.data['appKey'] = self.app_key
        self.data['salt'] = str(uuid.uuid1())
        self.data['signType'] = "v3"
        self.data['curtime'] = str(int(time.time()))

    def set_headers(self, dic: dict):
        for k, v in dic.items():
            self.headers[k] = v

    def request(self, q: str, m_from: str, m_to: str):
        """发起请求"""
        self.set_data()
        self.data['q'] = q.encode("utf-8").decode()
        self.data['from'] = self.language[m_from]
        self.data['to'] = self.language[m_to]
        self.data['sign'] = self.get_sign(q)
        self.response = requests.post(url=self.api, data=self.data, headers=self.headers).json()

    def get_response(self):
        if self.response.get("translation"):
            return self.response['translation'][0]
        return "对不起我还在学习"


if __name__ == '__main__':
    t = Translation("你的应用id", "你的应用密钥")
    #     # print(t.get_language())
    t.set_language("Language.json")
    t.set_headers({"content-type": "application/x-www-form-urlencoded"})
    t.request("hello world", "英文", "中文")
    print(t.get_response())
    t.request("hello world", "英文", "日文")
    print(t.get_response())

